package com.demo.jdk.thread;

import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 测试线程池LinkedBlockingQueue
 */
public class ThreadQueue {

    public void linkedBlockingQueue() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 500; i++) {
            executorService.execute(new TestRunable(i, countDownLatch));
        }
        countDownLatch.countDown();
    }

    public void arrayBlockingQueue() {
        ExecutorService executorService = new ThreadPoolExecutor(10, 10,
                0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(10));
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 20; i++) {
            executorService.execute(new TestRunable(i, countDownLatch));
        }
        countDownLatch.countDown();
    }

    public void synchronousQueue() {
        ExecutorService executorService = new ThreadPoolExecutor(0, 11,
                0L, TimeUnit.MILLISECONDS,
                new SynchronousQueue<>());

        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 11; i++) {
            executorService.execute(new TestRunable(i, countDownLatch));
        }
        countDownLatch.countDown();
    }

    public void delayQueue() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

        for (int i = 0; i < 2; i++) {
            executorService.scheduleAtFixedRate(new ScheduleRunable(i), 1,1, TimeUnit.SECONDS);
        }
    }

    public static void main(String[] args) {
        ThreadQueue threadQueue = new ThreadQueue();
//        threadQueue.linkedBlockingQueue();
//        threadQueue.arrayBlockingQueue();
//        threadQueue.synchronousQueue();
        threadQueue.delayQueue();
    }
}
